package fr.umlv.m2.jee.spij.ldap.actors.Mapper;

import fr.umlv.m2.jee.spij.ldap.actors.*;
import org.springframework.ldap.core.AttributesMapper;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;

/**
 * methods to map the attributes in the server LDAP to Actor Object.
 *
 * @author lounes
 */
public class ActorAttributeMapper implements AttributesMapper {

    @Override
    public final Object mapFromAttributes(final Attributes attributes)
            throws NamingException {

        Actor actor = typeOfActor(attributes);

        String login = (String) attributes.get("uid").get();
        if (login != null) {
            actor.setLogin(login);
        }

        String lastName = (String) attributes.get("givenName").get();
        if (lastName != null) {
            actor.setLastName(lastName);
        }

        String firstName = (String) attributes.get("sn").get();
        if (firstName != null) {
            actor.setFirstName(firstName);
        }

        String mail = (String) attributes.get("mail").get();
        if (mail != null) {
            actor.setMail(mail);
        }

        return actor;
    }

    /**
     * return the Actor type from  attributes in the LDAP server.
     *
     * @param attributes the attributes.
     *
     * @return type of Actor
     *
     * @throws NamingException if an exception occured.
     */
    private Actor typeOfActor(final Attributes attributes)
            throws NamingException {
        String cn = (String) attributes.get("cn").get();
        if ("Student".equals(cn)) {
            return new Student();
        }
        if ("Teacher".equals(cn)) {
            return new Teacher();
        }
        if ("Administrative".equals(cn)) {
            return new Administrative();
        }
        if ("Administrator".equals(cn)) {
            return new Administrator();
        }
        return null;
    }
}

